package org.zjx.resource;

import com.alibaba.fastjson2.JSON;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 资源文件解密
 */
public class ResourceDecryptor {
    private static final String ALGORITHM = ResourceEncryptor.ALGORITHM;

    // 解密并从文件中加载对象
    public static <T> T decryptFromFile(String filePath, SecretKey key, Class<T> classType) throws Exception {
        byte[] decryptedData = decryptFromFileToBytes(filePath, key);

        // 将解密后的字节数据转换为 JSON 字符串
        String json = new String(decryptedData, StandardCharsets.UTF_8);

        // 反序列化 JSON 字符串为对象
        return JSON.parseObject(json, classType);
    }

    // 从文件中解密字节数据
    private static byte[] decryptFromFileToBytes(String filePath, SecretKey key) throws Exception {
        try (FileInputStream fileInputStream = new FileInputStream(filePath);
             CipherInputStream cipherInputStream = new CipherInputStream(fileInputStream, getCipher(Cipher.DECRYPT_MODE, key))) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = cipherInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }

    // 解密输入流中的数据
    public static byte[] decryptFromStream(InputStream encryptedInputStream, SecretKey key) throws Exception {
        try (CipherInputStream cipherInputStream = new CipherInputStream(encryptedInputStream, getCipher(Cipher.DECRYPT_MODE, key))) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = cipherInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }

    // 获取 Cipher 实例
    private static Cipher getCipher(int mode, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(mode, key);
        return cipher;
    }


}